import os

from PIL import Image
from torch.utils.data import Dataset


class WaterSegmentation(Dataset):
    def __init__(self, root, transform=None):
        self.root = root
        self.transform = transform
        self.file_names = [name for name in os.listdir(self.root) if name.endswith('.jpg')]
        self.images = [os.path.join(self.root, name) for name in self.file_names]
        self.masks = [os.path.join(self.root, name.replace('.jpg', '.png')) for name in self.file_names]

    def __len__(self):
        return len(self.file_names)

    def __getitem__(self, index):
        # Load image
        image = Image.open(self.images[index]).convert('RGB')

        # Load masks
        target = Image.open(self.masks[index]).convert('L')

        if self.transform:
            image, target = self.transform(image, target)

        return image, target
